/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.servlet;

import java.util.Stack;
import offset.nodes.Constants;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

/**
 *
 * @author Walter L�tgenau
 */
public class ResidualNameFilter extends EmptyFilter implements XMLFilter {
    class Name {
        String uri;
        String localName;
        String qName;

        public Name(String uri, String localName, String qName) {
            this.uri = uri;
            this.localName = localName;
            this.qName = qName;
        }

        public String getLocalName() {
            return localName;
        }

        public String getQName() {
            return qName;
        }

        public String getUri() {
            return uri;
        }
        
    }
    
    Stack<Name> stack = new Stack<Name>();
    SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        String nameProperty = atts.getValue(QName.NAME_PROPERTY.getLocalName());
        if (nameProperty != null) {
            stack.push(new Name("", nameProperty, nameProperty));
            
            AttributesImpl attributes = new AttributesImpl(atts);
            attributes.removeAttribute(atts.getIndex(QName.NAME_PROPERTY.getLocalName()));
            if (attributes.getValue(Constants.JCR_PRIMARY_TYPE) == null)
                attributes.addAttribute(null, null, Constants.JCR_PRIMARY_TYPE, "CDATA", qName);
            atts = attributes;
        }
        else
            stack.push(new Name(uri, localName, qName));
        
        outputHandler.startElement(stack.peek().getUri(), stack.peek().getLocalName(), stack.peek().getQName(), atts);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        Name name = stack.pop();
        outputHandler.endElement(name.getUri(), name.getLocalName(), name.getQName());
    }


}
